const HtmlWebpackPlugin = require('html-webpack-plugin');
/**
 * 次插件是为了让webpack编译时自动插入link 或 script标签
 * 支持自定义path
 * @options { css: string[], js: string[] }
 */
class InsertTagPlugin {
  constructor(options) {
    this.options = options || {};
  }

  apply(compiler) {
    const cssPath = this.options.css || [];
    const jsPath = this.options.js || [];

    compiler.hooks.compilation.tap('InsertTagPlugin', (compilation) => {
      HtmlWebpackPlugin.getHooks(compilation).beforeAssetTagGeneration.tap(
        'InsertTagPlugin',
        (data) => {
          data.assets.css = [...cssPath, ...data.assets.css];
          data.assets.js = [...jsPath, ...data.assets.js];
        },
      );

      HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tap(
        'InsertTagPlugin',
        (htmlPluginData) => {
          const chunkScript = {
            tagName: 'script',
            closeTag: true,
            attributes: {
              type: 'text/javascript',
            },
            innerHTML: 'window.SeeyonUi = window.SeeyonUI',
          };
          htmlPluginData.assetTags.scripts.splice(2, 0, chunkScript);
        },
      );
    });
  }
}

module.exports = InsertTagPlugin;
